<!--
 * @Description: 
 * @Author: zhangwei
 * @Date: 2023-03-17 20:55:48
 * @LastEditTime: 2023-03-18 13:23:07
 * @LastEditors: zhangwei
-->
<!--
    表单的校验规则在每个表单项上面，不统一添加
-->

<script lang="tsx">

import { PropType, defineComponent, ref, unref, onMounted } from 'vue'
import type { FormSchema } from "../../../types/lowcode"
import { formCmpMap } from '../../index'
import type { FormInstance } from 'element-plus'

export default defineComponent({
    name: 'ZwForm',
    props: {
        schema: {
            type: Object as PropType<FormSchema>,
            default: function () { return {} }
        },
    },
    emits: [],
    setup(props, { expose }) {

        const formRef = ref<FormInstance>()


        onMounted(()=>{
            console.log("form init")
        })

        //watch()
        const renderWrap = () => {
            const { widgets = [], data } = unref(props.schema)
            return widgets.filter((v) => !v.hidden).map(item => {
                const Com = formCmpMap[item.component as string] as ReturnType<typeof defineComponent>
                return <Com schema={item} v-model={data[item.key]}></Com>
            })
        }

        const validate = (callbackFn) => {//查询操作，返回查询对象     
            unref(formRef)?.validate((isValid) => {
                if (isValid) {
                    callbackFn()
                }
            })
        }

        expose({
            validate,
        })

        return () => (
            <el-form model={props.schema.data} {...props.schema.attrs} ref={formRef}>
                {{

                    default: function () {
                        return renderWrap()
                    }
                }}

            </el-form>
        )
    }
})
</script>

<style lang="less" scoped></style>